<template>
    <view class="login-container">
        <view class="" v-if="!isWxauth">
            <view class="login-header" :style="{paddingTop: barHeight + 'px'}">
                <view class="header-view">
                    <view class="" @click="handleClose">
                        <u-icon name="close" size="32"></u-icon>
                    </view>
                    <view class="" @click="handleLoginType">
                        {{ login_type === 'account' ? '验证码登录' : '密码登录' }}
                    </view>
                </view>
                <view class="logo">
                    <image class="img" src="/static/images/huangjin/login.png" mode="widthFix"></image>
                </view>
            </view>
            <view class="login-cont">
                <view class="login-view login-quick" v-if="login_type === 'quick'">
                    <view class="form-view">
                        <u-form :model="quickForm" ref="quickForm">
                            <u-form-item label-position="top">
                                <u-input v-model="quickForm.mobile" maxlength="11" placeholder="请输入手机号" />
                            </u-form-item>
                            <u-form-item label-position="top">
                                <u-input v-model="quickForm.captcha" placeholder="请输入图片验证码" maxlength="4" />
                                <u-image slot="right" width="120" height="60" :src="captcha_url" @click="handleChangeCaptchalUrl"></u-image>
                            </u-form-item>
                            <u-form-item label-position="top">
                                <u-input v-model="quickForm.sms_code" placeholder="请输入短信验证码" maxlength="6" />
                                <u-button slot="right" type="error" size="mini" @click="handleCode">{{codeTips}}</u-button>
                                <u-verification-code seconds="60" ref="uCode" @change="handleCodeChange"></u-verification-code>
                            </u-form-item>
                        </u-form>
                        <view class="u-text-right login-text">
                            <navigator url="/mine-module/haibao/register" hover-class="none">手机注册?</navigator>
                        </view>
                        <u-button :disabled="login_disabled_quick" class="u-m-20" type="error" shape="circle" @click="handleLogin">登录</u-button>
                        <view class="agreement u-flex">
                            <u-checkbox v-model="policyCheck" size="24" active-color="#FD5B00" @change="checkboxChange"></u-checkbox>
                            <view class="agreement-text">
                                我已阅读并同意<text class="txt" @click="showPolicy = true">《{{site.site_name}}隐私政策》</text>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="login-view login-account" v-if="login_type === 'account'">
                    <view class="form-view">
                        <u-form :model="accountForm" ref="accountForm">
                            <u-form-item label-position="top">
                                <u-input v-model="accountForm.username" placeholder="请输入用户名" />
                            </u-form-item>
                            <u-form-item label-position="top">
                                <u-input v-model="accountForm.password" type="password" placeholder="请输入密码" />
                            </u-form-item>
                            <u-form-item label-position="top">
                                <u-input v-model="accountForm.captcha" placeholder="请输入图片验证码" maxlength="4" />
                                <u-image slot="right" width="120" height="60" :src="captcha_url" @click="handleChangeCaptchalUrl"></u-image>
                            </u-form-item>
                        </u-form>
                        <view class="u-text-right login-text">
                            <navigator url="/pages/auth/reset" hover-class="none">忘记密码?</navigator>
                        </view>
                        <u-button :disabled="login_disabled_account" class="u-m-20" type="error" shape="circle"
                            @click="handleLogin">登录</u-button>

                    </view>
                </view>
            </view>
            <!-- 因上架AppStore，暂时先去掉快捷登录。TODO 许立鹏 -->
            <!-- /*  */ -->
            
        </view>
        <view class="wx-auth-container u-m-50" v-else>
            <view class="logo-info u-text-center">
                <u-image class="u-flex u-row-center" :src="site.logo" width="400" height="100"></u-image>
                <view class="u-m-t-25">{{ site.site_name }}登录</view>
            </view>
            <u-line />
            <view class="tips-view">
                <view class="title">
                    {{ site.site_name }}小程序正在使用{{ site.site_name }}登录提供的服务，{{ site.site_name }}登录将使用：
                </view>
                <view class="tip">
                    <text class="u-m-r-15">●</text>
                    您的公开信息（昵称、头像、性别等）
                </view>
            </view>
            <view class="btns-view">
                <u-button :custom-style="customStyle" hover-class="none" :hair-line="false" open-type="getUserInfo"
                    @getuserinfo="wxLoginAuth">允许使用</u-button>
                <u-button :hair-line="false" hover-class="none" @click="handleCancel">取消</u-button>
            </view>
        </view>
        <!-- 隐私政策弹出层 -->
        <u-popup class="policy-view" v-model="showPolicy" mode="bottom" length="70%" border-radius="20"
            :safe-area-inset-bottom="true">
            <view class="u-p-30 u-text-center" style="font-weight: 600;">
                {{ policy.article_name }}
            </view>
            <scroll-view scroll-y="true" class="policy-content" :style="{height: scrollHeight * 0.7 + 'px'}">
                <u-parse :html="policy.content"></u-parse>
            </scroll-view>
        </u-popup>
        <u-no-network></u-no-network>
    </view>
</template>
<script>
  /*
  
  <view class="login-footer">
      <u-divider class="">其它登录方式</u-divider>
      <view class="u-flex u-row-center u-margin-top-100">
          <!-- #ifdef H5 -->
          <view id="qqLoginBtn" class="u-margin-20" @click="qqLogin" v-show="!isWx">
              <u-icon name="qq-circle-fill" size="80" color="#47a7fa"></u-icon>
          </view>
          <view class="u-margin-20" @click="wxlogin" v-show="isWx">
              <u-icon name="weixin-circle-fill" size="80" color="#6FD680"></u-icon>
          </view>
          <view class="u-margin-20" @click="goAlipay" v-show="!isWx">
              <u-icon name="zhifubao-circle-fill" size="80" color="#00aaff"></u-icon>
          </view>
          <view class="u-margin-20" @click="weiboLogin" v-show="!isWx">
              <u-icon name="weibo-circle-fill" size="80" color="#EB764D"></u-icon>
          </view>
          <!-- #endif -->
          <!-- #ifdef APP-PLUS -->
          <view  class="u-margin-20" v-if="$u.os() == 'ios'" @click="appleLogin">
              <u-icon custom-prefix="custom-icon" name="logo-apple-fill" size="80"></u-icon>
          </view>
          <view id="qqLoginBtn" class="u-margin-20" @click="qqLogin">
               <u-icon name="qq-circle-fill" size="80" color="#47a7fa"></u-icon>
           </view>
          <view class="u-margin-20" @click="wxlogin">
              <u-icon name="weixin-circle-fill" size="80" color="#6FD680"></u-icon>
          </view>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <view class="u-margin-20">
              <button class="wx-button" open-type="getUserInfo" @getuserinfo="wxlogin" withCredentials="true">
                  <u-icon class="u-m-t-30" name="weixin-circle-fill" size="80" color="#6FD680"></u-icon>
              </button>
          </view>
          <!-- #endif -->
      </view>
  </view>
  
  */
  
  
    import * as API_Common from '@/api/common.js';
    import * as API_Connect from '@/api/connect.js';
    import * as API_Passport from '@/api/passport.js';
    import * as API_Members from '@/api/members.js';
    import * as API_Article from '@/api/article.js';
    import {
        RegExp
    } from '@/ui-utils/index.js'
    import Cache, {Keys} from '@/utils/cache.js';
    // const jweixin = require('jweixin-module');
    export default {
        data() {
            return {
                current: 0,
                // #ifdef MP
                barHeight: this.customBar, //状态栏+导航栏高度
                // #endif
                // #ifdef APP-PLUS || H5
                barHeight: this.statusBar, //状态栏高度
                // #endif
                uuid: Cache.getItem(Keys.uuid),
                captcha_url: '', //图片验证码
                //登录类型 密码登录: account 验证码登录: quick
                login_type: 'account',
                accountForm: {
                    username: '',
                    password: '',
                    captcha: '',
                    uuid: Cache.getItem(Keys.uuid), //图片验证码验证参数需要
                    scene: 'LOGIN' //图片验证码验证参数需要
                },
                quickForm: {
                    mobile: '',
                    captcha: '',
                    sms_code: '',
                    scene: 'LOGIN',
                },
                codeTips: '获取验证码',
                policyCheck: true, //已阅读并同意协议
                showPolicy: false, //显示协议
                policy: '', //协议内容
                scrollHeight: uni.getSystemInfoSync().windowHeight - 70, //协议内容滚动高度
                site: Cache.getItem(Keys.site),
                // #ifdef MP
                isWxauth: false, //Cache.getItem(Keys.wxauth), //是否微信授权
                // #endif
                // #ifdef APP-PLUS || H5
                isWxauth: false, //APP H5不需要授权，默认为true
                // #endif
                customStyle: {
                    color: '#ffffff',
                    fontSize: '34rpx',
                    lineHeight: '98rpx',
                    backgroundColor: '#FD5B00'
                },
                networkType: '', //网络状态
                isWx:false, //判断是否为微信浏览器
                // #ifdef H5
                redirect_uri: window.location.origin + "/pages/auth/logining",
                // #endif
                qq_app_id:'',
                back_url: '',
            }
        },
        onLoad(options) {
            //读取返回地址
            this.back_url = options.back_url;
            let $this = this
            //获取网络类型
            uni.getNetworkType({
                success(res) {
                    $this.networkType = res.networkType
                    if (res.networkType !== 'none') {
                        $this.handleChangeCaptchalUrl()
                        $this.getArticleDetail()
                    }
                }
            })
            // #ifdef H5
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                $this.isWx=true;
            }
            // #endif
            API_Connect.getQQAppid().then(res=>{
                $this.qq_app_id = res;
            })
        },
        onShow() {
            this.accountForm.username = uni.getStorageSync('mobile') || ''
            this.quickForm.mobile = uni.getStorageSync('mobile') || ''
            let $this = this
            //监听网络状态变化
            uni.onNetworkStatusChange(res => {
                //监听到有网络并且第一次没有加载数据的情况下初始化数据
                if (res.isConnected && $this.networkType === 'none') {
                    $this.handleChangeCaptchalUrl()
                    $this.getArticleDetail()
                }
            })
            // const loginType = uni.getStorageSync('loginType')
            // if (loginType === 'weixin-auto-login') {
            //   uni.showLoading({ title: '登陆中...', mask: true })
            //   uni.removeStorageSync('loginType')
            // }
        },
        computed: {
            // 普通登录按钮 是否禁用
            login_disabled_account() {
                const {
                    username,
                    password,
                    captcha
                } = this.accountForm
                return !(username && password && captcha)
            },
            // 短信登录按钮 是否禁用
            login_disabled_quick() {
                const {
                    captcha,
                    mobile,
                    sms_code
                } = this.quickForm
                return !(captcha && mobile && sms_code)
            }
        },
        methods: {
            //允许使用（微信授权）
            wxLoginAuth() {
                let that = this
                uni.getSetting({
                    success(res) {
                        if (res.authSetting['scope.userInfo']) {
                            that.toAutoLogin()
                            setTimeout(() => {
                                that.isWxauth = true
                                Cache.setItem(Keys.wxauth, true)
                            }, 1000)
                        }
                    }
                })
            },
            wxlogin() {
                var that = this;
                // #ifdef H5
                API_Connect.wxH5GetLoginUrl(encodeURIComponent(this.redirect_uri)).then(res => {
                    // uni.setStorageSync('loginType', 'weixin-auto-login')
                    location.href = res;
                })
                // #endif
                // #ifndef H5
                uni.login({
                    provider: 'weixin',
                    success: function(loginRes) {
                        // #ifdef MP
                        // 获取用户信息
                        uni.getUserInfo({
                            provider: 'weixin',
                            success: function(info) {
                                const params = {
                                    edata: info.encryptedData,
                                    iv: info.iv,
                                    code: loginRes.code,
                                    uuid: Cache.getItem('uuid')
                                }
                                API_Connect.wxMiniLogin(params).then(response=>{that.loginCallback(response,true)})
                            },
                            fail(e) {
                            }
                        })
                        // #endif
                        // #ifdef APP-PLUS
                        const params = {
                            openid: loginRes.authResult.openid,
                            unionid: loginRes.authResult.unionid,
                            accessToken: loginRes.authResult.access_token,
                            refreshToken: loginRes.authResult.refresh_token
                        }
                        API_Connect.wxAppLogin(Cache.getItem('uuid'), params).then(response=>{that.loginCallback(response,true)})
                        // #endif
                    },
                    fail: function(res) {}
                })
                // #endif
            },
            //QQ授权登陆
            qqLogin() {
                var that = this;
                // #ifdef APP-PLUS
                uni.login({
                    provider: "qq",
                    success: (resp) => {
                        var access_token = resp.authResult.access_token;
                        uni.getUserInfo({
                            provider: 'qq',
                            success: function(infoRes) {
                                console.log('infoRes',infoRes)
                                const params = {
                                    openid: infoRes.userInfo.openId,
                                    headimgurl: infoRes.userInfo.figureurl_qq,
                                    accesstoken: access_token,
                                    nickname: infoRes.userInfo.nickname,
                                    gender: infoRes.userInfo.gender,
                                    province: infoRes.userInfo.province,
                                    city: infoRes.userInfo.city
                                }
                                API_Connect.qqAppLogin(Cache.getItem('uuid'), params).then(response=>{that.loginCallback(response,true)})
                            }
                        })
                    },
                    fail: (err) => {}
                });
                // #endif
                // #ifdef H5
                var that = this;
               QC.Login.showPopup({ //打开QQ授权登录界面，授权成功后会重定向
                   appId: that.qq_app_id,
                   redirectURI: that.redirect_uri //登录成功后会自动跳往该地址
               });
                 // #endif
            },
            //appleID登录
            appleLogin(){
                var that = this;
                // #ifdef APP-PLUS
                uni.login({
                    provider: 'apple',
                    success: function (loginRes) {
                        console.log('login='+JSON.stringify(loginRes))
                        // 登录成功
                        uni.getUserInfo({
                            provider: 'apple',
                            success(userInfoRes) {
                                // 获取用户信息成功
                                console.log('userInfoRes='+JSON.stringify(userInfoRes))
                                const params = {
                                    openid: userInfoRes.userInfo.openId,
                                }
                                API_Connect.appleAppLogin(params).then(response=>{that.loginCallback(response,true)})
                            }
                        })
                    },
                    fail: function (err) {
                        that.$u.toast('登录失败，请稍后重试');
                        // 登录失败
                    }
                });
                // #endif
            },
            //跳转到支付宝去要授权
            goAlipay(){
                // #ifdef H5
                API_Connect.aliPayGetLoginUrl(encodeURIComponent(this.redirect_uri)).then(res=>{
                    window.location.href=res;
                })
                // #endif
            },
            weiboLogin(){
                var that = this;
                // #ifdef H5
                API_Connect.weiboGetLoginUrl(encodeURIComponent(this.redirect_uri)).then(res=>{
                    window.location.href=res;
                })
                // #endif
                // #ifdef APP-PLUS
                uni.login({
                    provider: "sinaweibo",
                    success: (resp) => {
                        console.log("resp",resp)
                        uni.getUserInfo({
                            provider: 'sinaweibo',
                            success: function(infoRes) {
                                let params = {
                                    uuid:Cache.getItem('uuid'),
                                    unionid:infoRes.userInfo.id,
                                    headimgurl:infoRes.userInfo.profile_image_url,
                                    nickName:infoRes.userInfo.screen_name,
                                    sex:infoRes.userInfo.gender=="m"?1:0
                                }
                                API_Connect.weiboAppLogin(params).then(response=>{that.loginCallback(response,true)})
                            }
                        })
                    },
                    fail: (err) => {}
                });
                // #endif
            },
            // 取消
            handleCancel() {
                uni.navigateBack()
            },
            //小程序自动登录
            async toAutoLogin() {
                // 检测是否登录 如果已经登录 或者登录结果为账户未发现 则不再进行自动登录
                if (Cache.getItem(Keys.accessToken) || Cache.getItem(Keys.loginResult) === 'account_not_found')
                    return
                let final = {}
                let that = this
                const codeResult = await uni.login({
                    provider: 'weixin',
                    timeout: 8000
                })
                const {
                    code
                } = codeResult[1]
                const uuid = this.uuid
                try {
                    let result = await API_Connect.loginByAuto({
                        code,
                        uuid
                    })
                    // 如果已经进行过用户授权但是没有获取到unionID
                    if (result.reson === 'unionid_not_found') {
                        const {
                            encryptedData,
                            iv
                        } = await uni.getUserInfo({
                            withCredentials: true,
                            lang: 'zh_CN'
                        })
                        final = await API_Connect.accessUnionID({
                            code,
                            uuid,
                            encrypted_data: encryptedData,
                            iv
                        })
                    }
                    Cache.setItem(Keys.loginResult, result.reson)

                    const {
                        access_token
                    } = result.access_token ? result : final
                    // 如果登录成功 存储access_token
                    if (access_token) {
                        Cache.setItem(Keys.accessToken, access_token)
                        // 获取用户信息 获取购物车信息
                        const user = await API_Members.getUserInfo()
                        Cache.setItem(Keys.user, user)
                        uni.navigateBack()
                    }
                } catch (e) {
                    uni.setStorageSync('loginResult', false)
                }
            },
            //获取隐私政策
            getArticleDetail() {
                API_Article.getArticlesByPosition('REGISTRATION_AGREEMENT').then(response => {
                    this.policy = response
                })
            },
            // 获取图片验证码
            handleChangeCaptchalUrl() {
                this.captcha_url = API_Common.getValidateCodeUrl(this.uuid, 'LOGIN')
            },
            //返回上一页
            handleClose() {
				this.back()
				// uni.navigateBack()
            },
			back() {
				// #ifdef H5
				const pages = getCurrentPages()
					if (pages.length > 1) {
					uni.navigateBack(1)
					return
				}
				//使用vue-router返回上一级
				let a = this.$router.go(-1)
				if (a == undefined) {
					//重新定向跳转页面
					// uni.switchTab({
					//     url: '/pages/tabs/mine/mine'
					// });
					uni.navigateTo({
					    url: '/pages/tabs/mine/mine'
					});
				}
				return
				// #endif
				uni.navigateBack(1)
			},
            // 获取短信验证码
            handleCode() {
                if (this.$refs.uCode.canGetCode) {
                    // 向后端请求验证码
                    //如果是微信小程序
                    if (this.isWxauth) {
                        API_Connect.sendMobileLoginSms(this.quickForm.mobile, this.quickForm.captcha, this.uuid).then(
                            res => {
                                this.$u.toast('验证码已发送')
                                // 通知验证码组件内部开始倒计时
                                this.$refs.uCode.start()
                            }).catch(this.handleChangeCaptchalUrl)
                    } else {
                        API_Passport.sendLoginSms(this.quickForm).then(res => {
                            this.$u.toast('验证码已发送')
                            // 通知验证码组件内部开始倒计时
                            this.$refs.uCode.start()
                        }).catch(this.handleChangeCaptchalUrl)
                    }
                } else {
                    this.$u.toast('倒计时结束后再发送')
                }
            },
            //验证码发生变化时
            handleCodeChange(text) {
                this.codeTips = text;
            },
            //选择阅读并同意协议
            checkboxChange(e) {
                this.policyCheck = e.value
            },
            //登录类型
            handleLoginType() {
                if (this.login_type === 'account') {
                    this.login_type = 'quick'
                } else {
                    this.login_type = 'account'
                }
            },
            //登录
            handleLogin() {
                var that = this;
                if (!this.policyCheck) {
                    this.$u.toast('请勾选并同意《' + this.site.site_name + '隐私政策》')
                    return false
                }
                const login_type = this.login_type
                const form = login_type === 'quick' ? this.quickForm : this.accountForm
                // form.uuid = this.uuid
                if (login_type === 'quick') {
                    if (!form.mobile || !RegExp.mobile.test(form.mobile) || !form.sms_code) {
                        this.$u.toast('表单填写有误，请检查！')
                        return false
                    }
                    if (this.isWxauth) {
                        API_Connect.loginByMobileConnect(this.uuid, form).then(response=>{that.loginCallback(response,true)}).catch(this.handleChangeCaptchalUrl)
                    } else {
                        API_Passport.loginByMobile(this.quickForm).then(response=>{that.loginCallback(response,true)}).catch(this.handleChangeCaptchalUrl)
                    }
                } else {
                    if (!form.username || !form.password || !form.captcha) {
                        this.$u.toast('表单填写有误，请检查！')
                        return false
                    }
                    if (this.isWxauth) {
                        API_Connect.loginBindConnectByAccount(this.uuid, form).then(response=>{that.loginCallback(response,true)}).catch(this.handleChangeCaptchalUrl)
                    } else {
                        API_Passport.login(form).then(response=>{that.loginCallback(response,true)}).catch(this.handleChangeCaptchalUrl)

                    }
                }
                uni.setStorageSync('mobile', this.accountForm.username || this.quickForm.mobile)
            },
            //登录回调
            loginCallback(response,backToBefore) {
                Cache.setItem(Keys.accessToken, response.access_token)
                Cache.setItem(Keys.refreshToken, response.refresh_token)
                API_Members.getUserInfo().then(res => {
                    Cache.setItem(Keys.user, res)
                    uni.$emit('login', {
                        msg: '登录消息'
                    })
                    if(backToBefore){
                        // #ifndef H5
                        uni.navigateBack({
                            delta: 1,
                            animationType: 'slide-out-bottom',
                            animationDuration: 300
                        })
                        // #endif
                        // #ifdef H5
                        if (this.$u.test.isEmpty(this.back_url)){
                            this.back()
                        } else {
                            uni.reLaunch({
                                url: this.back_url
                            });
                        }
                        // #endif
                    }else{
                       // uni.switchTab({
                       //     url: '/pages/tabs/mine/mine'
                       // });
                       uni.navigateTo({
                           url: '/pages/tabs/mine/mine'
                       });
                    }

                })
            }
        }
    }
</script>

<style lang="scss" scoped>
    page{
        background-color: #fff;
    }
    .login-container {
        .login-header {
            // background-image: url(../../static/images/bg/bg5.png);
            // background-size: 100% 100%;
            color: #FFFFFF;
            padding: 30rpx;
            height: 500rpx;
            background-color: #FD5B00;

            .header-view {
                padding: 8rpx 0;
                display: flex;
                justify-content: space-between;
            }

            .logo {
                display: flex;
                justify-content: center;
                margin-top: 70rpx;

                .img {
                    width: 500rpx;
                    height: 100rpx;
                }
            }
        }

        .login-cont {
            width: 100%;

            .login-view {
                background-color: #FFFFFF;
                margin: -140rpx 30rpx 30rpx 30rpx;
                border-radius: 20rpx;
                padding: 20rpx 40rpx;
                box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);

                .login-text {
                    margin-top: 30rpx;
                    color: #82848A;
                    font-size: 24rpx;
                }

                .agreement {
                    padding: 20rpx 10rpx;
                    /deep/.u-checkbox {
                        display: inline-block;
                    }

                    .agreement-text {
                        font-size: 22rpx;

                        .txt {
                            // color: $u-type-error;
                            color: #FD5B00;
                        }
                    }
                }
            }
        }

        .login-footer {
            margin-top: 100rpx;
        }

        .policy-content {
            padding: 0 30rpx 20rpx 30rpx;
            box-sizing: border-box;
        }
    }

    .wx-auth-container {
        padding-top: 200rpx;

        .logo-info {
            font-size: 45rpx;
            font-weight: 600;
            margin-bottom: 45rpx;
        }

        .tips-view {
            .title {
                font-size: 30rpx;
                font-weight: 600;
                margin: 45rpx 0 30rpx 0;
            }

            .tip {
                color: #909399;
            }
        }

        .btns-view {
            margin: 100rpx 0;
        }

        /deep/ .u-btn--bold-border {
            border: none !important;
        }
    }

    .wx-button {
        background-color: #ffffff !important;

        &::after {
            border: none !important;
        }
    }
</style>
